package com.wosai.teach.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;

import com.lidroid.xutils.view.annotation.ContentView;
import com.umeng.message.PushAgent;
import com.wosai.teach.R;
import com.wosai.teach.cst.C;
import com.wosai.teach.entity.AppUseInfo;
import com.wosai.teach.entity.User;

@ContentView(R.layout.activity_splash)
public class SplashActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		PushAgent.getInstance(this).onAppStart();
		control();
	}

	/**
	 * 控制跳转
	 */
	private void control() {
		AppUseInfo aui = db.getFirst(AppUseInfo.class);
		if (aui == null) {
			aui = new AppUseInfo();
			aui.setFirstUse(true);
		}
		if (aui.isFirstUse()) {
			aui.setFirstUse(false);
			db.saveOrUpdate(aui);
			// 第一次
			toFirstUse();
			return;
		}
		User user = db.findFirst(User.class);
		if (aui.isLogin() && aui.getUserId() != null
				&& aui.getUserId().equals(user.getUserId())) {
			// 去主页面
			toMain();
		} else {
			// 去登录页面
			toLogin();
		}
	}

	private void toFirstUse() {
		Intent intent = new Intent(SplashActivity.this, WelcomActivity.class);
		startActivityForResult(intent, C.REQUEST_CODE_WELCOM);
	}

	private void toMain() {
		Intent intent = new Intent(SplashActivity.this, MainActivity.class);
		startActivity(intent);
	}

	private void toLogin() {
		Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.splash, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == C.REQUEST_CODE_WELCOM) {
			control();
		}
	}

}
